package com.example.allshengmedical.system.activity;

import java.text.BreakIterator;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.graphics.drawable.BitmapDrawable;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings.SettingNotFoundException;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.SeekBar;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.SeekBar.OnSeekBarChangeListener;

import com.example.allshengmedical.R;
import com.example.allshengmedical.base.BaseActivity;
import com.example.allshengmedical.base.BaseApplication;
import com.example.allshengmedical.mainmenu.activity.MainMenuActivity;
import com.example.allshengmedical.system.presenter.SystemPresenter;
import com.example.allshengmedical.system.view.ISystemView;
import com.example.allshengmedical.util.ByAlert;
import com.example.allshengmedical.util.SharedPreferencesUtils;
import com.itboye.allshengmedical.sci.DefaultSerialControl;
import com.itboye.allshengmedical.sci.ISerialControl;
import com.itboye.allshengmedical.sci.cmd.req.CmdType;
import com.itboye.allshengmedical.sci.packet.resp.BaseRespPacket;

public class SystemActivity extends BaseActivity implements ISystemView, OnClickListener {

	private LinearLayout toolLine, hourLine, languageLine, brightnessLine, maintenanceLine, helpLine;
	private SystemPresenter systemPresenter;
	boolean isOver = false;
	// 亮度调节
	SeekBar bar;
	ISerialControl controlInstance;
	int nowBrite = 50;
	PopupWindow popupWindow;
	boolean isCancle = false;

	@Override
	protected int setcontent() {
		return R.layout.activity_system;
	}

	@Override
	protected void initView() {
		systemPresenter = new SystemPresenter(this);
		systemPresenter.initAppHead();

	}

	@Override
	protected void initData() {

	}

	@Override
	public void toolFunction() {
		Intent intent = new Intent(SystemActivity.this, ToolActivity.class);
		startActivity(intent);
		finish();

	}

	@Override
	public void timeFunction() {
		Intent intent = new Intent(SystemActivity.this, ChangeHourActivity.class);
		startActivity(intent);
		finish();

	}

	@Override
	public void languageFunction(View v) {
		languagePopupWindow(v);

	}

	@Override
	public void brightnessFunction(View v) {
		brightnessPopupWindow(v);

	}

	@Override
	public void maintenanceFunction() {
		Intent intent = new Intent(SystemActivity.this, MaintenanceActivity.class);
		startActivity(intent);
		finish();

	}

	@Override
	public void helpFunction() {
		// ByAlert.alert("跳转6");

		ByAlert.alert("V:" + getVersion() + "安装时间：" + getCreateTime());

	}

	@Override
	public void initAppHead() {
		setSystemTime();
		setActionBar();

	}

	// 获取当前时间的方法
	public void setSystemTime() {

		TextView date, fileName;
		date = BindView(R.id.date);
		fileName = BindView(R.id.file_name);

		// 获取系统时间
		SimpleDateFormat sdfDate = new SimpleDateFormat("MM dd,yyyy");
		date.setText(sdfDate.format(new Date()));

		// 文件路径置空
		fileName.setText("");

	}

	// 设置actionBar
	public void setActionBar() {
		Button leftfirstBtn;
		TextView title;

		leftfirstBtn = BindView(R.id.leftfirst_btn);
		title = BindView(R.id.title);

		leftfirstBtn.setVisibility(View.VISIBLE);
		leftfirstBtn.setText(R.string.item_actionbar_home);
		title.setText(R.string.mainActivity_system);

		leftfirstBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent intent = new Intent(SystemActivity.this, MainMenuActivity.class);
				startActivity(intent);
				finish();
			}
		});

	}

	// 国际化弹窗
	private void languagePopupWindow(View v) {
		View conteView = LayoutInflater.from(this).inflate(R.layout.dialog_system_language, null);
		final Switch selectLine;
		Button confirmBtn;

		selectLine = (Switch) conteView.findViewById(R.id.select_line);
		confirmBtn = (Button) conteView.findViewById(R.id.confirm_btn);

		String sta = getResources().getConfiguration().locale.getLanguage();
		if ("en".equals(sta)) {
			selectLine.setChecked(true);
		} else if ("zh".equals(sta)) {
			selectLine.setChecked(false);
		}

		final PopupWindow popupWindow = new PopupWindow(conteView, LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT,
				true);

		popupWindow.setTouchable(true);

		popupWindow.setTouchInterceptor(new OnTouchListener() {

			@Override
			public boolean onTouch(View v, MotionEvent event) {

				return false;
				// 这里如果返回true的话，touch事件将被拦截
				// 拦截后 PopupWindow的onTouchEvent不被调用，这样点击外部区域无法dismiss
			}

		});

		popupWindow.setBackgroundDrawable(new BitmapDrawable());
		popupWindow.setTouchable(true);
		popupWindow.setOutsideTouchable(true);
		popupWindow.showAtLocation(v, Gravity.CENTER, 0, 0);

		confirmBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if (selectLine.isChecked()) {
					// ByAlert.alert("true");

					shiftLanguage("zh");
					SharedPreferencesUtils.put(SystemActivity.this, BaseApplication.SYSTEM_LANGUAGE, "zh");
					popupWindow.dismiss();
				} else {
					// ByAlert.alert("false");

					shiftLanguage("en");
					SharedPreferencesUtils.put(SystemActivity.this, BaseApplication.SYSTEM_LANGUAGE, "en");
					popupWindow.dismiss();
				}

				BaseApplication.getInstance().finishAll();
				Intent intent = new Intent(SystemActivity.this, MainMenuActivity.class);
				startActivity(intent);
			}

		});

	}

	// 国际化控制
	private void shiftLanguage(String sta) {
		// TODO Auto-generated method stub
		Log.e("!!!", sta);
		if (sta.equals("zh")) {
			Locale.setDefault(Locale.ENGLISH);
			Configuration config = getBaseContext().getResources().getConfiguration();
			config.locale = Locale.ENGLISH;
			getBaseContext().getResources().updateConfiguration(config,
					getBaseContext().getResources().getDisplayMetrics());
			updateActivity();
		} else {
			Locale.setDefault(Locale.CHINA);
			Configuration config = getBaseContext().getResources().getConfiguration();
			config.locale = Locale.CHINA;
			getBaseContext().getResources().updateConfiguration(config,
					getBaseContext().getResources().getDisplayMetrics());
			updateActivity();
		}
	}

	// 刷新当前页面
	private void updateActivity() {
		// TODO Auto-generated method stub
		Intent intent = new Intent();
		intent.setClass(this, SystemActivity.class);// 当前Activity重新打开
		intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
		startActivity(intent);
	}

	private Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			switch (msg.what) {
			case ISerialControl.FindPacketMessage:
				String cmdType = msg.getData().getString("cmdType");
				BaseRespPacket packet = (BaseRespPacket) msg.getData().getSerializable("packet");

				if (cmdType.length() < 1)
					return;
				// 根据type 转换packet 为你想要的
				CmdType type = CmdType.getCmdType(cmdType.substring(1));
				// 发送指令后这里会收到数据
				Log.e("hu_data", "接受到的响应数据包是" + cmdType + type.toDesc());
				switch (type) {
				case LightJustTemp:
					if (isCancle) {
						controlInstance.pause();
					}
					break;
				}
				break;
			}
		};
	};

	// 亮度调节弹窗
	private void brightnessPopupWindow(View v) {
		View conteView = LayoutInflater.from(this).inflate(R.layout.dialog_system_brightness, null);

		Button confirmBtn, cancle_btn;

		bar = (SeekBar) conteView.findViewById(R.id.select_line);
		confirmBtn = (Button) conteView.findViewById(R.id.confirm_btn);
		cancle_btn = (Button) conteView.findViewById(R.id.cancle_btn);
		screenBrightness_check();
		popupWindow = new PopupWindow(conteView, LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, true);
		popupWindow.setTouchable(true);
		popupWindow.setTouchInterceptor(new OnTouchListener() {

			@Override
			public boolean onTouch(View v, MotionEvent event) {

				return false;
				// 这里如果返回true的话，touch事件将被拦截
				// 拦截后 PopupWindow的onTouchEvent不被调用，这样点击外部区域无法dismiss
			}

		});

		// popupWindow.setBackgroundDrawable(new BitmapDrawable());
		popupWindow.setTouchable(true);
		popupWindow.setOutsideTouchable(false);
		popupWindow.showAtLocation(v, Gravity.CENTER, 0, 0);

		confirmBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				SharedPreferencesUtils.put(SystemActivity.this, BaseApplication.BRIGHTNESS, "" + nowBrite);
				popupWindow.dismiss();
				controlInstance.pause();
			}
		});
		cancle_btn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				isCancle = true;
				controlInstance.addCommand(CmdType.LightJustTemp, null, Integer.parseInt(
						SharedPreferencesUtils.get(SystemActivity.this, BaseApplication.BRIGHTNESS, "80") + ""));
				popupWindow.dismiss();
				// controlInstance.pause();
			}
		});
		bar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {

			@Override
			public void onStopTrackingTouch(SeekBar seekBar) {
				// TODO Auto-generated method stub
				if (seekBar.getProgress() >= 0 && seekBar.getProgress() <= 100) {
					controlInstance = DefaultSerialControl.getInstance();
					controlInstance.init();
					controlInstance.start();
					controlInstance.setHandler(handler);
					controlInstance.addCommand(CmdType.LightJustTemp, null, seekBar.getProgress());
					nowBrite = seekBar.getProgress();
				}
			}

			@Override
			public void onStartTrackingTouch(SeekBar seekBar) {
				// TODO Auto-generated method stub

			}

			@Override
			public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
				// setScreenBritness(progress);

			}
		});

	}

	// Handler handler = new Handler() {
	// @Override
	// public void handleMessage(Message msg) {
	// // TODO Auto-generated method stub
	// super.handleMessage(msg);
	// switch (msg.what) {
	// case ISerialControl.FindPacketMessage:
	// // 完成主界面更新,拿到数据
	// SharedPreferencesUtils.put(SystemActivity.this,
	// BaseApplication.BRIGHTNESS, "" + nowBrite);
	// isOver = true;
	// // controlInstance.pause();
	// break;
	// case ISerialControl.SCTimeoutMessage:
	// isOver = true;
	// ByAlert.alert("超时");
	// popupWindow.dismiss();
	// controlInstance.release();
	// break;
	// default:
	// break;
	// }
	// }
	// };

	private void screenBrightness_check() {
		bar.setProgress(Integer
				.parseInt(SharedPreferencesUtils.get(SystemActivity.this, BaseApplication.BRIGHTNESS, "80") + ""));
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.toolLine:
			systemPresenter.toolFunction();
			break;
		case R.id.hourLine:
			systemPresenter.timeFunction();
			break;
		case R.id.languageLine:
			systemPresenter.languageFunction(v);
			break;
		case R.id.brightnessLine:
			systemPresenter.brightnessFunction(v);
			break;
		case R.id.maintenanceLine:
			systemPresenter.maintenanceFunction();
			break;
		case R.id.helpLine:
			systemPresenter.helpFunction();
			break;

		default:
			break;
		}
	}

	/**
	 * 获取版本号
	 * 
	 * @return 当前应用的版本号
	 */
	public String getVersion() {
		try {
			PackageManager manager = BaseApplication.getContext().getPackageManager();
			PackageInfo info = manager.getPackageInfo(BaseApplication.getContext().getPackageName(), 0);
			String version = info.versionName;
			return version;
		} catch (Exception e) {
			e.printStackTrace();
			return "暂无";
		}
	}

	public String getCreateTime() {
		long firstInstallTime, lastUpdateTime = 0;
		try {
			PackageManager packageManager = BaseApplication.getContext().getPackageManager();
			PackageInfo packageInfo = packageManager.getPackageInfo(BaseApplication.getContext().getPackageName(), 0);
			// 应用装时间
			firstInstallTime = packageInfo.firstInstallTime;
			// 应用最后一次更新时间
			lastUpdateTime = packageInfo.lastUpdateTime;
			// LogUtil.debug("first install time : " + firstInstallTime + " last
			// update time :" + lastUpdateTime);

		} catch (PackageManager.NameNotFoundException e) {
			e.printStackTrace();
		}
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd hh:mm");
		return df.format(lastUpdateTime);

	}

}
